using System;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Service.Operation.Dto;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Admin.NET.Application.Service.EarlyWarnings;

public class EarlyWarningService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<EarlyWarning> _rep;

	private readonly UserManager _userManager;

	public EarlyWarningService(UserManager userManager, SqlSugarRepository<EarlyWarning> rep)
	{
		_userManager = userManager;
		_rep = rep;
	}

	[HttpPost("/earlywarning/disposeOne")]
	public async Task DisposeOne(BaseIdInput input)
	{
		EarlyWarning entity = await _rep.GetFirstAsync((EarlyWarning u) => u.Id == input.Id);
		if (entity != null)
		{
			DateTime now = DateTime.Now;
			entity.EndTime = now;
			entity.StartTime = now;
			entity.OperateUserId = _userManager.UserId;
			entity.OperateUserName = _userManager.RealName;
			entity.ProcessingResults = "处理完成";
			entity.Status = 2;
			await _rep.UpdateAsync(entity);
		}
	}

	[HttpPost("/earlywarning/disposeAll")]
	public async Task DisposeAll()
	{
		DateTime now = DateTime.Now;
		await (from u in _rep.Context.Updateable<EarlyWarning>()
			where u.Status == 0
			select u).SetColumns((EarlyWarning u) => u.StartTime == now).SetColumns((EarlyWarning u) => u.EndTime == now).SetColumns((EarlyWarning u) => u.OperateUserId == (long?)_userManager.UserId)
			.SetColumns((EarlyWarning u) => u.OperateUserName == _userManager.RealName)
			.SetColumns((EarlyWarning u) => u.Status == 2)
			.SetColumns((EarlyWarning u) => u.ProcessingResults == "处理完成")
			.ExecuteCommandAsync();
	}

	/// <summary>
	/// 分页查询
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/earlywarning/page")]
	public async Task<dynamic> Page([FromQuery] OperationLogInput input)
	{
		ISugarQueryable<EarlyWarning> query = from x in _rep.Context.Queryable<EarlyWarning>()
			where x.CreateTime >= input.StartTime && x.CreateTime <= input.EndTime
			select x;
		query = query.OrderBy((EarlyWarning u) => u.Status).OrderBuilder(input);
		return await query.ToPagedListAsync(input.Page, input.PageSize);
	}
}
